package net.htjs.juc.sleepwait;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

/**
 * 保护性暂停模式
 * */
@Slf4j
public class Demo5 {

    private static final GuardeObject object = new GuardeObject();

    public static void main(String[] args) throws InterruptedException {
        GuardeObject guardeObject = new GuardeObject();
        new Thread(() -> {
            log.info("等待结果");
            List<String> lines = (List<String>) guardeObject.get();
            log.info("结果是大小:{}", lines.size());
        }, "t1").start();

        new Thread(() -> {
            log.info("执行下载");
            try {
                List<String> lines = Downloader.download();
                guardeObject.complete(lines);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, "t2").start();
    }

    static class GuardeObject {
        private Object response;
        //获取结果
        public Object get() {
            while(response == null) {
                synchronized (this) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            return response;
        }

        public void complete(Object response) {
            synchronized (this) {
                //给结果成员变量赋值
                this.response = response;
                this.notifyAll();
            }
        }
    }

}
